//
//  PreviewViewController.m
//  JXW_UnionSDK
//
//  Created by 彭月辉 on 2022/6/23.
//

#import "PreviewViewController.h"
#import <MobileVLCKit/MobileVLCKit.h>
#import "Masonry.h"
#import <ADSEFramework/ADSELinkManager.h>

#import "RemoteFileViewController.h"
#import "SettingTableViewController.h"

#import "LCRecordCounter.h"

@interface PreviewViewController ()<VLCMediaPlayerDelegate>{
    
    VLCMediaPlayer *vlcPlayer;
    UIView *playview;
    
    UIButton *btn_setting;
    UIButton *btn_mode;
    UIButton *btn_record;
    UIButton *btn_snapshot;
    UIButton *btn_remote;
    UIButton *btn_format;
    UIButton *btn_disconnect;

    LCRecordCounter *recordcounter;
    
    NSArray *menuList;
    NSArray *streams;
    
    NSInteger recloop;
    
    BOOL isNewNationalStandard;
}

@end

@implementation PreviewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationItem setHidesBackButton:YES];
    
    recloop = 1;
    [self initUI];

//    //连接设备
//    NSInteger ret = [[ADSELinkManager shareInstance] connect];
//    NSLog(@"连接设备 --> %@",ret == 0 ? @"成功":@"失败");
    
    //获取设备SSID
//    [[ADSELinkManager shareInstance]getWiFiSSID:^(NSInteger code, NSString * _Nullable name) {
//        if(code == LINK_ERR_OK){
//            self.title = name;
//        }
//    }];
    
    //同步时间
    [[ADSELinkManager shareInstance] syncTime:^(NSInteger code,NSInteger state) {
        if(state == LINK_ERR_OK){
            
        }
        else{
            NSLog(@"同步时间 error --> %ld",code);
        }
    }];
    
    //获取菜单信息
    [[ADSELinkManager shareInstance] getMenuList:^(NSInteger code, NSArray * _Nullable list) {
        if(code == LINK_ERR_OK){
            menuList = list;
            [menuList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                ADSELinkSDKCMDModel *model = obj;
                if(model.cmd == LINK_CMD_VIDEO_LOOP_REC){
                    NSArray *options =  model.options;
                    [options enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        ADSELinkSDKOptionModel *opModel = obj;
                        if(model.active == 1){
                            recloop = opModel.index;
                            *stop = YES;
                        }
                    }];
                    *stop = YES;
                }
            }];
        }
        else{
            NSLog(@"获取菜单 error --> %ld",code);
        }
    } cache:NO];


    //获取预览地址
     [[ADSELinkManager shareInstance] getStreamURL:^(NSInteger code, NSArray * _Nullable list) {
         if(code == LINK_ERR_OK){
             streams = list;
             if([streams count] > 0){
                 [self initVLCPlayer:[streams firstObject]];
             }
         }
         else{
             NSLog(@"获取预览地址 error --> %ld",code);
         }

    }];
    
    //查询是否新国标机器
    [[ADSELinkManager shareInstance] isMultipleStorageSupported:^(NSInteger code, NSInteger state) {
         if(code == LINK_ERR_OK){
             isNewNationalStandard = state;
         }
         else{
             NSLog(@"查询机器是否多存储 error --> %ld",code);
         }
    }];
    
    
    //用于接收机器下发的通知
    [ADSELinkManager shareInstance].notifyBlock = ^(LinkNotifyCode type, NSString *valueString) {
        NSLog(@"type --> %d,value --> %@",type,valueString);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self handleDeviceNotifycation:type value:valueString];
        });
    };


    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self setVideoModel];

}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [[ADSELinkManager shareInstance] isPhotoModelSupported:^(NSInteger code, NSInteger state) {
        if(code == LINK_ERR_OK && state){
            btn_mode.enabled = YES;
            [btn_mode setBackgroundColor:[UIColor blueColor]];
        }
        else{
            btn_mode.enabled = NO;
            [btn_mode setBackgroundColor:[UIColor lightGrayColor]];
        }
    }];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(vlcPlayer.isPlaying){
        [vlcPlayer stop];
    }
}


- (void)appEnterForeground{
    [[ADSELinkManager shareInstance] openNotify:^(NSInteger code) {
        if(code == LINK_ERR_OK){
            NSLog(@"打开通知成功");
        }
        else{
            NSLog(@"打开通知失败");
        }
    }];
}

- (void)appEnterBackground{
    [[ADSELinkManager shareInstance] closeNotify];
}

- (void)settingAction:(UIButton *)sender{
    if(btn_record.selected){
        [self showError:@"请先停止录像"];
        return;
    }
    SettingTableViewController *settingVC = [[SettingTableViewController alloc] init];
    [self.navigationController pushViewController:settingVC animated:YES];
    
    settingVC.settingBlock = ^(int cmd, NSString *value) {
        if(cmd == 1001){
            recloop = [value intValue];
        }
    };
}

- (void)setVideoModel{
    
    [SVProgressHUD show];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //切换录像模式
        [[ADSELinkManager shareInstance] setWorkMode:LINK_WORKMODE_VIDEO callback:^(NSInteger code, NSInteger state) {
            //查看录像状态
            [self checkRecStatus];

            //播放器重刷
            dispatch_async(dispatch_get_main_queue(), ^{
                if(code == LINK_ERR_OK){
                    NSLog(@"切换模式 ok");
                    btn_mode.selected = NO;
                    btn_snapshot.selected = NO;
                }
                else{
                    NSLog(@"切换模式 error --> %ld",code);
                }

                if(!vlcPlayer.playing){
                    [self refreshPlayer];
                }
            });
        }];

    });
}

- (void)checkRecStatus{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        __block BOOL flag = NO;
        [[ADSELinkManager shareInstance] getVideoRecStatus:^(NSInteger code, NSInteger state) {
            if(code == LINK_ERR_OK){
                if(state){
                    NSLog(@"录像状态:开");
                    flag = YES;
                }
                else{
                    NSLog(@"录像状态:关");
                    flag = NO;
                }
            }
        }];
        
        if(!flag){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                recordcounter.hidden = YES;
            });
            return;
        }
        
        [[ADSELinkManager shareInstance] queryRecSeconds:^(NSInteger code, NSInteger seconds) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                if(code == LINK_ERR_OK){
                    NSLog(@"获取录像时间 ok : %ld",seconds);

                    recordcounter.hidden = NO;
                    [recordcounter startRecord:YES time:(int)seconds cycleRecordTime:recloop * 60];
                }
                else{
                    NSLog(@"获取当前录像时长失败");
                }
                btn_record.selected = YES;
            });
        }];
        
    });
    
}


- (void)setMode:(UIButton *)sender{
    if(btn_record.selected){
        [self showError:@"请先停止录像"];
        return;
    }
    
    LinkWorkMode mode;
    if(btn_mode.selected){
        mode = LINK_WORKMODE_VIDEO;
    }
    else{
        mode = LINK_WORKMODE_PHOTO;
    }
    
    [SVProgressHUD show];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[ADSELinkManager shareInstance] setWorkMode:mode  callback:^(NSInteger code, NSInteger state) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];

                if(code == LINK_ERR_OK){
                    NSLog(@"切换模式成功");
                    btn_mode.selected = mode == LINK_WORKMODE_VIDEO ? NO : YES;
                    btn_snapshot.selected = btn_mode.selected;
                }
                else{
                    NSLog(@"切换模式失败");
                }
                [self refreshPlayer];
            });
        }];

    });
    
    /*
    [[ADSELinkManager shareInstance] getWorkMode:^(NSInteger code, LinkWorkMode mode) {
        if(code == LINK_ERR_OK){
            LinkWorkMode setmode = mode == LINK_WORKMODE_VIDEO ? LINK_WORKMODE_PHOTO : LINK_WORKMODE_VIDEO;
        }
    }];
    */
}

- (void)recordAction:(UIButton *)sender{
    if(btn_mode.selected){
        [self showError:@"当前非录像模式"];
        return;
    }
    sender.selected = !sender.selected;

    BOOL isSelected = sender.selected;
    
    __block BOOL flag = NO;
    if(!isNewNationalStandard && isSelected){
        [[ADSELinkManager shareInstance] getExternalStorageState:^(NSInteger code, NSInteger state) {
            if(code == LINK_ERR_OK){
                if(state == LINK_CARD_OK){
                    flag = YES;
                }
                else{
                    NSString *error = [self convertCardStatusToString:state];
                    [self showError:error];
                    flag = NO;
                }
            }
            else{
                [self showError:@"请求失败"];
                flag = NO;
            }
        }];
    }
    else{
        flag = YES;
    }
    if(!flag){
        sender.selected = !sender.selected;
        return;
    }
    
    [SVProgressHUD show];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[ADSELinkManager shareInstance] setVideoRecState:isSelected callback:^(NSInteger code,NSInteger state) {
            if(code == LINK_ERR_OK){
                if(isSelected){
                    [[ADSELinkManager shareInstance] queryRecSeconds:^(NSInteger code, NSInteger seconds) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if(code == LINK_ERR_OK){
                                [SVProgressHUD dismiss];
                                recordcounter.hidden = NO;
                                [recordcounter startRecord:YES time:(int)seconds cycleRecordTime:recloop * 60];
                            }
                            else{
                                NSLog(@"获取当前录像时长失败");
                            }
                        });
                    }];
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                        recordcounter.hidden = YES;
                    });
                }
            }
            else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    recordcounter.hidden = YES;
                    sender.selected = !sender.selected;
                    [self showError:@"录像出错"];
                });
            }
        }];
    });

}


- (void)snapshotAction:(UIButton *)sender{

    sender.userInteractionEnabled = NO;
    
    if(sender.selected){
        [[ADSELinkManager shareInstance] takePhoto:^(NSInteger code, NSInteger state) {
            if(code == LINK_ERR_OK){
                [SVProgressHUD showInfoWithStatus:@"拍照成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    sender.userInteractionEnabled = YES;
                });
            }
            else{
                [SVProgressHUD showInfoWithStatus:@"拍照失败"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    sender.userInteractionEnabled = YES;
                });
            }
        }];
    }
    else{
        if(!btn_record.selected){
            [self showError:@"当前不在录像状态"];
            sender.userInteractionEnabled = YES;
            return;
        }
        [[ADSELinkManager shareInstance] snapshot:^(NSInteger code, NSInteger state) {
            if(code == LINK_ERR_OK){
                [SVProgressHUD showInfoWithStatus:@"截图成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    sender.userInteractionEnabled = YES;
                });
            }
            else{
                [SVProgressHUD showInfoWithStatus:@"截图失败"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    sender.userInteractionEnabled = YES;
                });
            }
        }];
    }
    
}


- (void)getRemoteFileAction:(UIButton *)sender{
    if(btn_record.selected){
        [self showError:@"请先停止录像"];
        return;
    }

    /**/
    //单存储切回放模式，坏卡会死机！！！！！！！！
    
    [SVProgressHUD show];
    __block BOOL flag = NO;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //查看回放文件先切到回放模式（此操作略微耗时，可放子线程处理）
        [[ADSELinkManager shareInstance] setWorkMode:LINK_WORKMODE_PLAYBACK callback:^(NSInteger code, NSInteger state) {
            if(code == LINK_ERR_OK){
                flag = YES;
                NSLog(@"切换回放模式成功");
            }
            else{
//                [self showError:@"切换回放模式失败"];
                NSLog(@"切换回放模式失败");
                flag = NO;
            }
        }];

        
        if(!flag) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            return;
        }

        //判断是否支持切换存储区域
        [[ADSELinkManager shareInstance] isStorageSelectSupported:^(NSInteger code,NSInteger state) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                if(code == LINK_ERR_OK){
                    if(state){
                        RemoteFileViewController *remotefileVC = [[RemoteFileViewController alloc] init];
                        remotefileVC.title = @"Files";
                        [self.navigationController pushViewController:remotefileVC animated:YES];
                    }
                    else{
                        [self showAlertToSelectStorage];
                    }
                }
                else{
                    NSLog(@"错误 --> %ld",code);
                }
            });
            
        }];
                
    });
    
}

- (void)showAlertToSelectStorage{
    __block BOOL flag = NO;

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@""
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *TFAction = [UIAlertAction actionWithTitle:@"TF卡" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [SVProgressHUD show];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [[ADSELinkManager shareInstance] getExternalStorageState:^(NSInteger code, NSInteger state) {
                if(code == LINK_ERR_OK && state == LINK_CARD_OK){
                    flag = YES;
                }
                else{
                    flag = NO;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                        [self showError:@"TF状态异常"];
                    });
                }

            }];
            
            if(!flag) { return; }
            [[ADSELinkManager shareInstance] storageSelect:LINK_STORAGE_EXTERNAL callback:^(NSInteger code, NSInteger state) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];

                    if(code == LINK_ERR_OK ){
                        RemoteFileViewController *remotefileVC = [[RemoteFileViewController alloc] init];
                        remotefileVC.type = LINK_STORAGE_EXTERNAL;
                        remotefileVC.title = @"TF卡";
                        [self.navigationController pushViewController:remotefileVC animated:YES];
                    }
                    else{
                        [self showError:@"切换存储区域失败"];
                    }
                });
            }];
        });
    }];

    
    UIAlertAction *eMMCAction = [UIAlertAction actionWithTitle:@"eMMC" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [[ADSELinkManager shareInstance] storageSelect:LINK_STORAGE_INTERNAL callback:^(NSInteger code, NSInteger state) {
                if(code == LINK_ERR_OK ){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                        RemoteFileViewController *remotefileVC = [[RemoteFileViewController alloc] init];
                        remotefileVC.type = LINK_STORAGE_INTERNAL;
                        remotefileVC.title = @"eMMC";
                        [self.navigationController pushViewController:remotefileVC animated:YES];
                    });
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                        [self showError:@"切换eMMC失败"];
                    });
                }
            }];
        });
       
    }];
                                 
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];

    [alertController addAction:eMMCAction];
    [alertController addAction:TFAction];
    [alertController addAction:cancelAction];

    [self presentViewController:alertController animated:YES completion:nil];

    
}


- (void)formatAction:(UIButton *)sender{
    
    if(btn_record.selected){
        [self showError:@"请先停止录像"];
        return;
    }

    //判断是否支持格式化
    [[ADSELinkManager shareInstance] isInternalStorageFormatSupported:^(NSInteger code, NSInteger isSupport) {
        if(code == LINK_ERR_OK){
            if(isSupport){
                if(!isNewNationalStandard){
                    [[ADSELinkManager shareInstance] getExternalStorageState:^(NSInteger code, NSInteger state) {
                        if(code == LINK_ERR_OK){
                            if(state == LINK_CARD_OK){
                                [[ADSELinkManager shareInstance] formatStorage:LINK_STORAGE_INTERNAL callback:^(NSInteger code, NSInteger fmstate) {
                                    if(fmstate == LINK_ERR_OK){
                                        NSLog(@"已格式化TF卡");
                                        [self showError:@"TF卡已格式化"];
                                    }
                                    else{
                                        NSLog(@"格式化TF卡失败");
                                        [self showError:@"格式化TF卡失败"];
                                    }
                                }];
                            }
                            else{
                                [self showError:[self convertCardStatusToString:state]];
                            }

                        }
                        else{
                            [self showError:@"格式化卡失败"];
                        }
                    }];
                    return;
                };
                
                
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"选择格式化区域"
                                                                                         message:@""
                                                                                  preferredStyle:UIAlertControllerStyleActionSheet];
                
                UIAlertAction *eMMCAction = [UIAlertAction actionWithTitle:@"eMMC" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    [[ADSELinkManager shareInstance] formatStorage:LINK_STORAGE_INTERNAL callback:^(NSInteger code, NSInteger state) {
                        if(code == LINK_ERR_OK){
                            NSLog(@"已格式化eMMC");
                            [self showError:@"eMMC已格式化"];
                        }
                        else{
                            NSLog(@"格式化eMMC失败");
                            [self showError:@"格式化eMMC失败"];
                        }

                    }];

                }];
                
                UIAlertAction *TFAction = [UIAlertAction actionWithTitle:@"TF卡" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    
                    [[ADSELinkManager shareInstance] getExternalStorageState:^(NSInteger code, NSInteger state) {
                        if(code == LINK_ERR_OK){
                            
                            [[ADSELinkManager shareInstance] formatStorage:LINK_STORAGE_INTERNAL callback:^(NSInteger code, NSInteger state) {
                                if(code == LINK_ERR_OK){
                                    NSLog(@"已格式化TF卡");
                                    [self showError:@"TF卡已格式化"];
                                }
                                else{
                                    NSLog(@"格式化TF卡失败");
                                    [self showError:@"格式化TF卡失败"];
                                }

                            }];

                        }
                        else{
                            NSLog(@"请求失败");
                            [self showError:@"请求失败，请重试"];
                        }
                    }];
                                    
                }];

                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];

                [alertController addAction:eMMCAction];
                [alertController addAction:TFAction];
                [alertController addAction:cancelAction];

                [self presentViewController:alertController animated:YES completion:nil];
            }
            else{
                NSLog(@"不支持格式化存储区域");
            }
        }
        else{
            NSLog(@"请求失败 --> %ld",code);
        }
        
    }];
    
}


- (void)disconnectAction:(UIButton *)sender{
//    if(btn_record.selected){
//        [self showError:@"请先停止录像"];
//        return;
//    }
    [[ADSELinkManager shareInstance] disconnect];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 机器通知处理

- (void)handleDeviceNotifycation:(LinkNotifyCode)code value:(NSString *)info{
    
    //录像开始
    if(code == LINK_NOTIFY_REC_STARTED){
        
        NSLog(@"录像开始");

        recordcounter.hidden = NO;
        btn_record.selected = YES;
        [recordcounter startRecord:YES time:0 cycleRecordTime:recloop * 60];
        if(btn_mode.selected){
            btn_mode.selected = NO;
            [[ADSELinkManager shareInstance] setWorkMode:LINK_WORKMODE_VIDEO callback:^(NSInteger code, NSInteger state) {
                if(code == LINK_ERR_OK){
                    NSLog(@"录像模式切换成功");
                    [self refreshPlayer];
                }
                else{
                    NSLog(@"录像模式切换失败");
                }
            }];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"RecordStartNotification" object:nil];

    }
    
    //录像结束
    else if(code == LINK_NOTIFY_REC_STOPPED){
        btn_record.selected = NO;
        recordcounter.hidden = YES;
    }
    
    //麦克风开
    else if(code == LINK_NOTIFY_MIC_ON){
        [self showError:@"麦克风已打开"];
    }
    
    //麦克风关
    else if(code == LINK_NOTIFY_MIC_OFF){
        [self showError:@"麦克风已关闭"];    }
    
    //卡插入
    else if(code == LINK_NOTIFY_CARD_INSERT){
        [self showError:@"SD卡已插入"];
    }
    
    //卡拔出
    else if(code == LINK_NOTIFY_CARD_REMOVE){
        [self showError:@"SD卡已拔出"];
    }
    
    //卡满
    else if(code == LINK_NOTIFY_CARD_FULL){
        [self showError:@"SD卡已满"];
    }

    //慢卡
    else if(code == LINK_NOTIFY_CARD_SLOW){
        [self showError:@"慢卡"];
    }

    //WiFi断开
    else if(code == LINK_NOTIFY_WIFI_DISCONNECT){
        [self disconnectAction:nil];
        [self showError:@"WiFi已断开"];
    }
    
    //断电
    else if(code == LINK_NOTIFY_POWER_OFF){
        [self disconnectAction:nil];
        [self showError:@"机器断电"];
    }

    /*
     *可继续添加需要监听的命令
     */


}

- (NSString *)convertCardStatusToString:(LinkStorageState)state{
    
    NSString *errorString = @"无卡";
    if(state == LINK_CARD_REMOVED){
        errorString = @"卡已移除";
    }
    else if (state == LINK_CARD_FULL){
        errorString = @"卡已满";
    }
    else if (state == LINK_CARD_READ_ONLY){
        errorString = @"卡不能写入";
    }
    else if (state == LINK_CARD_LOCKED){
        errorString = @"卡已锁定";
    }
    else if (state == LINK_CARD_UNFORMATTED){
        errorString = @"卡未格式化";
    }
    else if (state == LINK_CARD_UNKNOWN_FORMAT){
        errorString = @"未知格式的卡";
    }
    else if (state == LINK_CARD_BAD){
        errorString = @"坏卡";
    }
    else if (state == LINK_CARD_ERROR){
        errorString = @"卡错误";
    }
    return errorString;

}


- (void)initUI{
    playview = [[UIView alloc] init];
    [self.view addSubview:playview];
    
    playview.backgroundColor = [UIColor blackColor];
        
    
    btn_setting = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn_setting setTitle:@"设置" forState:UIControlStateNormal];
    [btn_setting setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn_setting addTarget:self action:@selector(settingAction:) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn_setting];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    btn_mode = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn_mode];

    [btn_mode setTitle:@"切拍照模式" forState:UIControlStateNormal];
    [btn_mode setTitle:@"切录像模式" forState:UIControlStateSelected];
    [btn_mode setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn_mode setBackgroundColor:[UIColor blueColor]];
    [btn_mode addTarget:self action:@selector(setMode:) forControlEvents:UIControlEventTouchUpInside];
    
    btn_record = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn_record];

    [btn_record setTitle:@"录像" forState:UIControlStateNormal];
    [btn_record setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn_record setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    [btn_record setBackgroundColor:[UIColor blueColor]];
    [btn_record addTarget:self action:@selector(recordAction:) forControlEvents:UIControlEventTouchUpInside];
    
    btn_snapshot = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn_snapshot];

    [btn_snapshot setTitle:@"截图" forState:UIControlStateNormal];
    [btn_snapshot setTitle:@"拍照" forState:UIControlStateSelected];
    [btn_snapshot setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn_snapshot setBackgroundColor:[UIColor blueColor]];
    [btn_snapshot addTarget:self action:@selector(snapshotAction:) forControlEvents:UIControlEventTouchUpInside];

    
    btn_remote = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn_remote];

    [btn_remote setTitle:@"回放" forState:UIControlStateNormal];
    [btn_remote setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn_remote setBackgroundColor:[UIColor blueColor]];
    [btn_remote addTarget:self action:@selector(getRemoteFileAction:) forControlEvents:UIControlEventTouchUpInside];

    
    btn_format = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn_format];

    [btn_format setTitle:@"格式化" forState:UIControlStateNormal];
    [btn_format setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn_format setBackgroundColor:[UIColor blueColor]];
    [btn_format addTarget:self action:@selector(formatAction:) forControlEvents:UIControlEventTouchUpInside];

    
    btn_disconnect = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn_disconnect];

    [btn_disconnect setTitle:@"断开连接" forState:UIControlStateNormal];
    [btn_disconnect setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn_disconnect setBackgroundColor:[UIColor blueColor]];
    [btn_disconnect addTarget:self action:@selector(disconnectAction:) forControlEvents:UIControlEventTouchUpInside];

    
    recordcounter = [[LCRecordCounter alloc] init];
    [self.view addSubview:recordcounter];
    
    recordcounter.hidden = YES;
    
    [playview mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        } else {
            make.top.equalTo(self.mas_topLayoutGuideBottom);
        }
        make.left.right.equalTo(@0);
        make.height.equalTo(@300);
    }];

    [btn_record mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(playview.mas_bottom).offset(50);
        make.width.equalTo(@100);
        make.height.equalTo(@60);
    }];
    
    [btn_mode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(btn_record);
        make.right.equalTo(btn_record.mas_left).offset(-30);
        make.width.equalTo(@100);
        make.height.equalTo(@60);
    }];
    
    
    [btn_snapshot mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(btn_record);
        make.left.equalTo(btn_record.mas_right).offset(20);
        make.width.equalTo(@100);
        make.height.equalTo(@60);
    }];
    
    
    [btn_remote mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(btn_record);
        make.top.equalTo(btn_record.mas_bottom).offset(20);
        make.left.equalTo(btn_mode.mas_left);
        make.height.equalTo(@60);
    }];
    
    [btn_disconnect mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(btn_remote.mas_bottom).offset(20);
        make.left.right.height.equalTo(btn_remote);
    }];
    
    [recordcounter mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(playview.mas_top).offset(0);
        make.width.equalTo(@100);
        make.height.equalTo(@30);
    }];


}

- (void)initVLCPlayer:(NSString *)url{
    vlcPlayer = [[VLCMediaPlayer alloc] initWithOptions:nil];
    vlcPlayer.delegate = self;
    vlcPlayer.drawable = playview;
//    vlcPlayer.media = [VLCMedia mediaWithURL:[NSURL URLWithString:url]];
//    [vlcPlayer play];
}

- (void)refreshPlayer{
    if([streams count] == 0){
        return;
    }
    ADSELinkSDKLiveStreamModel *streamModel = streams.firstObject;
    vlcPlayer.media = [VLCMedia mediaWithURL:[NSURL URLWithString:streamModel.liveURL]];
    [vlcPlayer play];
}

@end
